#!/bin/sh

# 设置严格模式
set -eu

# 定义常量和配置
export DMENU_FONT='JetBrainsMono Nerd Font'
export DMENU_NORMAL_BG='#181825'
export DMENU_NORMAL_FG='#adbac7'
export DMENU_SELECT_BG='#7ec9d8'
export DMENU_SELECT_FG='#181825'
export DMENU_LINES=6

# 定义默认的URL列表  
readonly DEFAULT_URLS=(  
    "https://www.baidu.com"  
    "https://fanyi.baidu.com/"
    "https://www.bilibili.com"
    "https://www.github.com"
    "https://www.nerdfonts.com"
    "https://www.gitee.com/wzy-20041202/i3-bspwm"
    "https://www.bootcdn.cn"
    "https://tetr.io/"
)  

# URL正则表达式模式
readonly URL_REGEX="(((http|https|gopher|gemini|ftp|ftps|git)://|www\\.)[a-zA-Z0-9.]*[:;a-zA-Z0-9./+@$&%?$\#=_~-]*)|((magnet:\\?xt=urn:btih:)[a-zA-Z0-9]*)"

# 显示帮助信息
show_help() {
    printf "Optional arguments for custom use:\\n  -c: copy\\n  -o: xdg-open\\n  -h: Show this message\\n"
    exit 0
}

# 使用dmenu显示URL列表
show_dmenu() {
    local prompt="$1"
    dmenu -fn "$DMENU_FONT" \
          -nb "$DMENU_NORMAL_BG" \
          -nf "$DMENU_NORMAL_FG" \
          -sf "$DMENU_SELECT_FG" \
          -sb "$DMENU_SELECT_BG" \
          -i \
          -p "$prompt" \
          -l "$DMENU_LINES"
}

# 获取URL列表
get_urls() {
    local include_defaults="$1"
    local urls_input
    urls_input="$(sed 's/.*│//g' | tr -d '\n' | uniq | sed "s/\(\.\|,\|\;\|\!\\|\?\)$//; s/^www./http:\/\/www\./")"
    
    # 从输入中提取URL
    local extracted_urls
    extracted_urls=$(echo "$urls_input" | grep -aEo "$URL_REGEX" | sort -u)
    
    if [ "$include_defaults" = "true" ]; then
        # 合并提取的URL和默认URL列表
        printf "%s\n" "$extracted_urls" "${DEFAULT_URLS[@]}" | sort -u | grep .
    else
        printf "%s\n" "$extracted_urls" | grep .
    fi
}

# 主函数
main() {
    # 处理命令行参数
    while getopts "hoc" opt; do
        case "$opt" in
            h) show_help ;;
            o) 
                # 打开URL时包含默认URL列表
                local urls=$(get_urls "true")
                [ -z "$urls" ] && exit 1
                local chosen
                chosen="$(echo "$urls" | show_dmenu 'Follow which url?')"
                [ -n "$chosen" ] && setsid xdg-open "$chosen" >/dev/null 2>&1 & 
                ;;
            c) 
                # 复制URL时不包含默认URL列表
                local urls=$(get_urls "false")
                [ -z "$urls" ] && exit 1
                echo "$urls" | show_dmenu 'Copy which url?' | tr -d '\n' | xclip -selection clipboard 
                ;;
            *) 
                printf "Invalid option: -%s\\n" "$OPTARG" >&2
                exit 1 
                ;;
        esac
    done
}

main "$@"
